package com.zhang.controller;


import com.alibaba.fastjson.JSONObject;
import com.zhang.constant.RedisConst;
import com.zhang.entity.UserInfo;
import com.zhang.result.RetVal;
import com.zhang.service.UserInfoService;
import com.zhang.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zbw
 * @since 2022-04-18
 */
@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.登录的认证逻辑
    @PostMapping("login")
    public RetVal login(@RequestBody UserInfo uiUserInfo, HttpServletRequest request){
        //1.根据用户账号密码查询数据库
        UserInfo dbUserInfo=userInfoService.queryUserFromDb(uiUserInfo);
        if (dbUserInfo!=null){
            Map<String, Object> retMap = new HashMap<>();
            //b.生成一个token给前端(cookie中)
            String token = UUID.randomUUID().toString();
            retMap.put("token",token);
            //返回用户昵称给前端页面
            String nickName = dbUserInfo.getNickName();
            retMap.put("nickName",nickName);
            //c.将用户信息放到redis中 user:login:xxxx
            String userKey= RedisConst.USER_LOGIN_KEY_PREFIX+token;
            JSONObject userInfoJson = new JSONObject();
            userInfoJson.put("userId",dbUserInfo.getId());
            userInfoJson.put("loginIp", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(userKey,userInfoJson,RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retMap);
        }else {
            return RetVal.fail().message("登录失败!");
        }
    }

    //2.登出的逻辑
    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request){
        String tokenValue = request.getHeader("token");
        //此时从request中无法拿到cookie
        //Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if("token".equals(cookie.getName())){
//                tokenValue = cookie.getValue();
//            }
//        }
        //因为退出时前端的auth中已经做了删除token和cookie的操作，因此后端只需要删除redis中的数据即可
        String userKey= RedisConst.USER_LOGIN_KEY_PREFIX+tokenValue;
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }
}